<?php
namespace app\services\admin;


class ChartService
{

    protected $barDefaultConfig = [
        'label' => 'bar',
        'fill' => false,
        'borderColor' => 'rgba(75, 192, 192, 0.3)',
        'borderWidth' =>  1,
    ];

    protected $lineDefaultConfig = [
        'label' => 'line',
        'fill' => false,
        'borderColor' => 'rgba(102, 102, 102, 0.9)',
        'borderWidth' => 2,
        'pointBackgroundColor' => 'rgba(75, 192, 192, 0.3)',
        'pointBorderWidth' => 2,
    ];

    protected $polarAreaDefaultConfig = [
        'label' => 'polarArea',
        'fill' => false,
        'borderColor' => 'rgb(255, 255, 255)',
        'borderWidth' => 2,
    ];

    public function __construct()
    {

    }

    public function randomColor($count = 1, $alpha = 0.4)
    {
        $bgColor = [];
        for ($j = 1; $j <= $count; $j++) {
            $color = [];
            for ($i = 1; $i <= 3; $i++) {
                $color[] = mt_rand(0, 255);
            }
            $color[] = $alpha;
            $strColor = implode(',', $color);
            $bgColor[] = "rgba($strColor)";
        }
        return $bgColor;
    }

    public function barChart($data, $options = [], $alpha = 0.4)
    {
        $datasets = array_merge($this->barDefaultConfig, [
            'backgroundColor' => $this->randomColor(count($data), $alpha),
            'data' => array_values($data),
        ], $options);

        return [
            'labels' => array_keys($data),
            'datasets' => [$datasets]
        ];
    }

    public function lineChart($data, $options = [], $alpha = 0.3)
    {
        $datasets = array_merge($this->lineDefaultConfig, [
            'backgroundColor' => $this->randomColor(1, $alpha),
            'data' => array_values($data),
        ], $options);

        return [
            'labels' => array_keys($data),
            'datasets' => [$datasets]
        ];
    }

    public function polarAreaChart($data, $options = [], $alpha = 0.6)
    {
        $datasets = array_merge($this->polarAreaDefaultConfig, [
            'backgroundColor' => $this->randomColor(count($data), $alpha),
            'data' => array_values($data),
        ], $options);

        return [
            'labels' => array_keys($data),
            'datasets' => [$datasets]
        ];
    }
}
